<template>
  <div class="coupon-consume">
    <!-- 页面标题 -->
    <!-- <div class="page-header">
      <h2>优惠券核销</h2>
      <p>执行优惠券核销操作，支持金额计算和详细记录</p>
    </div> -->

    <!-- 核销表单 -->
    <el-card class="consume-card">
      <div slot="header">
        <span>优惠券核销</span>
        <el-button style="float: right;" type="text" @click="goBack">返回</el-button>
      </div>

      <el-form :model="consumeForm" :rules="consumeRules" ref="consumeForm" label-width="120px">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <el-form-item label="优惠券代码" prop="coupon_code">
            <el-input 
              v-model="consumeForm.coupon_code" 
              placeholder="请输入优惠券代码"
              @blur="handleCouponCodeBlur">
              <template #append>
                <el-button icon="el-icon-camera" @click="showQrScanner">扫码</el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="核销商户" prop="merchant_id">
            <el-select
              v-model="consumeForm.merchant_id"
              placeholder="请选择核销商户"
              style="width: 300px;"
              clearable
              filterable
              :loading="merchantLoading"
              @change="verifyCoupon"
            >
              <el-option
                v-for="merchant in merchantList"
                :key="merchant.id"
                :label="`${merchant.merchant_name} (ID: ${merchant.id})`"
                :value="merchant.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 优惠券信息显示 -->
        <div v-if="couponInfo" class="coupon-info-section">
          <h3>优惠券信息</h3>
          <el-alert
            :title="verifyMessage"
            :type="canConsume ? 'success' : 'error'"
            show-icon
            :closable="false"
          />
          
          <el-descriptions border :column="2" style="margin-top: 20px;">
            <el-descriptions-item label="优惠券代码">{{ couponInfo.coupon_code }}</el-descriptions-item>
            <el-descriptions-item label="优惠券名称">{{ couponInfo.coupon_name }}</el-descriptions-item>
            <el-descriptions-item label="描述">{{ couponInfo.description }}</el-descriptions-item>
            <el-descriptions-item label="当前状态">
              <el-tag :type="couponInfo.is_consumed ? 'danger' : 'success'">
                {{ couponInfo.is_consumed ? '已消费' : '可使用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ couponInfo.create_time }}</el-descriptions-item>
            <el-descriptions-item label="所属商户">{{ merchantInfo ? merchantInfo.name : '未知' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 消费信息 -->
        <div v-if="canConsume" class="form-section">
          <h3>消费信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="原价金额" prop="original_amount">
                <el-input-number 
                  v-model="consumeForm.original_amount"
                  :precision="2"
                  :min="0"
                  placeholder="原价金额"
                  style="width: 100%;"
                  @change="calculateDiscount"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优惠金额" prop="discount_amount">
                <el-input-number 
                  v-model="consumeForm.discount_amount"
                  :precision="2"
                  :min="0"
                  placeholder="优惠金额"
                  style="width: 100%;"
                  @change="calculateConsume"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际消费" prop="consume_amount">
                <el-input-number 
                  v-model="consumeForm.consume_amount"
                  :precision="2"
                  :min="0"
                  placeholder="实际消费金额"
                  style="width: 100%;"
                  @change="calculateDiscount"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="核销类型" prop="consume_type">
            <el-radio-group v-model="consumeForm.consume_type">
              <el-radio :label="1">正常消费</el-radio>
              <el-radio :label="2">人工核销</el-radio>
              <el-radio :label="3">系统自动</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="核销渠道" prop="consume_channel">
            <el-select v-model="consumeForm.consume_channel" placeholder="请选择核销渠道" style="width: 200px;">
              <el-option label="商户端" value="merchant"></el-option>
              <el-option label="移动端" value="mobile"></el-option>
              <el-option label="网页端" value="web"></el-option>
              <el-option label="扫码" value="scan"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="操作员工" prop="operated_by_merchant_staff">
            <el-input 
              v-model="consumeForm.operated_by_merchant_staff" 
              placeholder="操作员工姓名"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item label="核销地点" prop="consume_location">
            <el-input 
              v-model="consumeForm.consume_location" 
              placeholder="核销地点"
              style="width: 300px;"
            ></el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="verification_code">
            <el-input 
              v-model="consumeForm.verification_code" 
              placeholder="验证码（可选）"
              style="width: 200px;"
            ></el-input>
          </el-form-item>

          <el-form-item label="核销备注" prop="consume_note">
            <el-input 
              type="textarea"
              v-model="consumeForm.consume_note"
              :rows="3"
              placeholder="核销备注说明"
              style="width: 500px;"
            ></el-input>
          </el-form-item>
        </div>

        <!-- 用户信息（可选） -->
        <div v-if="canConsume" class="form-section">
          <h3>
            用户信息（可选）
            <el-button 
              type="text" 
              size="small" 
              @click="autoFillUserInfo"
              :loading="userInfoLoading"
              style="margin-left: 10px;"
            >
              <i class="el-icon-refresh"></i> 自动获取
            </el-button>
          </h3>
          <el-alert
            v-if="(consumeForm.user_union_id || consumeForm.user_openid)"
            title="用户信息已从优惠券关联数据中自动获取"
            type="success"
            :closable="false"
            show-icon
            style="margin-bottom: 15px;"
          >
          </el-alert>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户UnionID">
                <el-input 
                  v-model="consumeForm.user_union_id" 
                  placeholder="微信UnionID"
                  style="width: 100%;"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户OpenID">
                <el-input 
                  v-model="consumeForm.user_openid" 
                  placeholder="微信OpenID"
                  style="width: 100%;"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitConsume" :loading="consumeLoading" :disabled="!canConsume">
            确认核销
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 核销确认对话框 -->
    <el-dialog
      title="确认核销"
      :visible.sync="confirmDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="confirm-content">
        <el-alert
          title="请确认核销信息"
          type="warning"
          show-icon
          :closable="false"
        />
        
        <div class="confirm-details">
          <p><strong>优惠券代码：</strong>{{ consumeForm.coupon_code }}</p>
          <p><strong>优惠券名称：</strong>{{ couponInfo ? couponInfo.coupon_name : '' }}</p>
          <p><strong>原价金额：</strong>¥{{ consumeForm.original_amount || '0.00' }}</p>
          <p><strong>优惠金额：</strong>¥{{ consumeForm.discount_amount || '0.00' }}</p>
          <p><strong>实际消费：</strong>¥{{ consumeForm.consume_amount || '0.00' }}</p>
          <p><strong>操作员工：</strong>{{ consumeForm.operated_by_merchant_staff || '未填写' }}</p>
          <p><strong>核销地点：</strong>{{ consumeForm.consume_location || '未填写' }}</p>
        </div>
        
        <el-alert
          title="核销后不可撤销，请确认信息无误！"
          type="error"
          show-icon
          :closable="false"
        />
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="doConsume" :loading="consumeLoading">确认核销</el-button>
      </span>
    </el-dialog>

    <!-- 核销成功对话框 -->
    <el-dialog
      title="核销成功"
      :visible.sync="successDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="success-content">
        <el-result
          icon="success"
          title="优惠券核销成功"
          :sub-title="`核销记录ID：${consumeResult ? consumeResult.record_id : ''}`"
        >
          <template slot="extra">
            <div class="success-details">
              <p><strong>优惠券代码：</strong>{{ consumeResult ? consumeResult.coupon_code : '' }}</p>
              <p><strong>核销时间：</strong>{{ consumeResult ? consumeResult.consume_time : '' }}</p>
              <p><strong>消费金额：</strong>¥{{ consumeResult ? consumeResult.consume_amount : '0.00' }}</p>
            </div>
            <el-button type="primary" @click="goToRecords">查看记录</el-button>
            <el-button @click="continueConsume">继续核销</el-button>
          </template>
        </el-result>
      </div>
    </el-dialog>

    <!-- 二维码扫描对话框 -->
    <el-dialog
      title="扫描二维码"
      :visible.sync="qrScannerVisible"
      width="650px"
      top="5vh"
      @close="stopScan">
      <div class="qr-scanner-container">
        <!-- 摄像头扫码区域 -->
        <div class="camera-scan-section">
          <div v-if="!showScanner" class="scan-placeholder">
            <i class="el-icon-camera scan-icon"></i>
            <p>点击按钮开启摄像头扫描优惠券二维码</p>
            <el-button type="primary" @click="startScan">开始扫码</el-button>
          </div>

          <div v-if="showScanner" class="scanner-container">
            <div class="scanner-wrapper">
              <video id="qr-scanner" style="width: 300px; height: 300px; border-radius: 8px;"></video>
              <div class="scanner-overlay">
                <div class="scan-frame"></div>
              </div>
            </div>
            <div class="scanner-controls">
              <el-button @click="stopScan">停止扫码</el-button>
              <el-button type="primary" @click="switchCamera" v-if="cameras.length > 1">切换摄像头</el-button>
            </div>
            <p class="scanner-tip">请将二维码对准扫描框</p>
          </div>
        </div>

        <!-- 手动输入选项 -->
        <div class="manual-input-section">
          <el-divider>或手动输入</el-divider>
          <el-form :model="qrForm" label-width="100px">
            <el-form-item label="二维码数据">
              <el-input
                v-model="qrForm.qr_data"
                type="textarea"
                :rows="3"
                placeholder="请粘贴二维码数据">
              </el-input>
            </el-form-item>
          </el-form>

          <div class="qr-scanner-actions">
            <el-button @click="parseQrCode" type="primary" :loading="qrParseLoading">
              解析二维码
            </el-button>
            <el-button @click="qrScannerVisible = false">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QrScanner from 'qr-scanner'
import {
  verifyCoupon as apiVerifyCoupon,
  consumeCoupon as apiConsumeCoupon,
  parseCouponQrCode,
  getMerchantList
} from '@/api/nfc'

export default {
  name: 'CouponConsume',
  data() {
    return {
      consumeForm: {
        coupon_code: '',
        merchant_id: '',
        consume_amount: null,
        original_amount: null,
        discount_amount: null,
        consume_note: '',
        consume_type: 1,
        consume_channel: 'merchant',
        operated_by_merchant_staff: '',
        consume_location: '',
        verification_code: '',
        user_union_id: '',
        user_openid: ''
      },
      
      // 商户列表
      merchantList: [],
      merchantLoading: false,

      couponInfo: null,
      merchantInfo: null,
      canConsume: false,
      verifyMessage: '',
      verifyLoading: false,
      consumeLoading: false,
      userInfoLoading: false,
      
      confirmDialogVisible: false,
      successDialogVisible: false,
      consumeResult: null,
      
      qrScannerVisible: false,
      qrParseLoading: false,
      qrForm: {
        qr_data: ''
      },

      // 摄像头扫码相关
      showScanner: false,
      scanner: null,
      cameras: [],
      currentCamera: 0,
      
      consumeRules: {
        coupon_code: [
          { required: true, message: '请输入优惠券代码', trigger: 'blur' },
          { max: 50, message: '优惠券代码不能超过50个字符', trigger: 'blur' }
        ],
        merchant_id: [
          { required: true, message: '请选择核销商户', trigger: 'change' },
          { 
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请选择核销商户'))
              } else if (Number(value) <= 0) {
                callback(new Error('商户ID必须大于0'))
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ],
        consume_type: [
          { required: true, message: '请选择核销类型', trigger: 'change' }
        ],
        consume_channel: [
          { required: true, message: '请选择核销渠道', trigger: 'change' }
        ]
      }
    }
  },
  async mounted() {
    // 从查询参数中获取预填数据
    const { coupon_code, merchant_id } = this.$route.query
    if (coupon_code) {
      this.consumeForm.coupon_code = coupon_code
    }

    // 加载商户列表
    await this.loadMerchantList()

    // 处理商户ID参数
    if (merchant_id) {
      this.setMerchantFromQuery(merchant_id)
    }

    // 如果有预填数据，自动验证
    if (coupon_code && this.consumeForm.merchant_id) {
      this.verifyCoupon()
    }
  },
  methods: {
    /**
     * 加载商户列表
     */
    async loadMerchantList() {
      this.merchantLoading = true
      try {
        const response = await getMerchantList()
        if (response.code === 200) {
          this.merchantList = response.data || []
        } else {
          this.$message.error(response.message || '获取商户列表失败')
        }
      } catch (error) {
        console.error('获取商户列表失败:', error)
        this.$message.error('获取商户列表失败')
      } finally {
        this.merchantLoading = false
      }
    },

    /**
     * 验证优惠券
     */
    async verifyCoupon() {
      if (!this.consumeForm.coupon_code || !this.consumeForm.merchant_id) {
        return
      }
      
      this.verifyLoading = true
      this.couponInfo = null
      this.merchantInfo = null
      this.canConsume = false
      
      try {
        const response = await apiVerifyCoupon({
          coupon_code: this.consumeForm.coupon_code,
          merchant_id: this.consumeForm.merchant_id
        })
        
        this.couponInfo = response.data.coupon
        this.merchantInfo = response.data.merchant
        this.canConsume = response.data.can_consume
        this.verifyMessage = response.message
        
        // 自动填充用户信息
        if (this.canConsume && response.data.user_info) {
          const userInfo = response.data.user_info
          if (userInfo.user_union_id || userInfo.user_openid) {
            this.consumeForm.user_union_id = userInfo.user_union_id || ''
            this.consumeForm.user_openid = userInfo.user_openid || ''
            this.$message.success('优惠券验证成功，已自动填充用户信息')
          } else {
            this.$message.success('优惠券验证成功，可以核销')
          }
        } else if (this.canConsume) {
          this.$message.success('优惠券验证成功，可以核销')
        } else {
          this.$message.warning(this.verifyMessage)
        }
        
      } catch (error) {
        this.verifyMessage = error.response?.data?.message || '验证失败'
        this.canConsume = false
        this.$message.error(this.verifyMessage)
      } finally {
        this.verifyLoading = false
      }
    },

    /**
     * 自动获取用户信息
     */
    async autoFillUserInfo() {
      if (!this.canConsume) {
        this.$message.warning('请先验证优惠券')
        return
      }
      
      this.userInfoLoading = true
      
      try {
        // 重新调用验证接口获取用户信息
        const response = await apiVerifyCoupon({
          coupon_code: this.consumeForm.coupon_code,
          merchant_id: this.consumeForm.merchant_id
        })
        
        if (response.data.user_info) {
          const userInfo = response.data.user_info
          if (userInfo.user_union_id || userInfo.user_openid) {
            this.consumeForm.user_union_id = userInfo.user_union_id || ''
            this.consumeForm.user_openid = userInfo.user_openid || ''
            this.$message.success('用户信息已自动填充')
          } else {
            this.$message.info('该优惠券未关联用户信息')
          }
        } else {
          this.$message.info('该优惠券未关联用户信息')
        }
        
      } catch (error) {
        this.$message.error('获取用户信息失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.userInfoLoading = false
      }
    },

    /**
     * 计算优惠金额
     */
    calculateDiscount() {
      if (this.consumeForm.original_amount && this.consumeForm.consume_amount) {
        this.consumeForm.discount_amount = Number((this.consumeForm.original_amount - this.consumeForm.consume_amount).toFixed(2))
      }
    },

    /**
     * 计算消费金额
     */
    calculateConsume() {
      if (this.consumeForm.original_amount && this.consumeForm.discount_amount) {
        this.consumeForm.consume_amount = Number((this.consumeForm.original_amount - this.consumeForm.discount_amount).toFixed(2))
      }
    },

    /**
     * 提交核销
     */
    async submitConsume() {
      if (!await this.validateForm()) return
      
      if (!this.canConsume) {
        this.$message.error('优惠券不能核销')
        return
      }
      
      this.confirmDialogVisible = true
    },

    /**
     * 执行核销
     */
    async doConsume() {
      this.consumeLoading = true
      
      try {
        const response = await apiConsumeCoupon(this.consumeForm)
        
        this.consumeResult = response.data
        this.confirmDialogVisible = false
        this.successDialogVisible = true
        
        this.$message.success('优惠券核销成功')
        
      } catch (error) {
        this.$message.error(error.response?.data?.message || '核销失败')
      } finally {
        this.consumeLoading = false
      }
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.$refs.consumeForm.resetFields()
      this.couponInfo = null
      this.merchantInfo = null
      this.canConsume = false
      this.verifyMessage = ''
    },

    /**
     * 继续核销
     */
    continueConsume() {
      this.successDialogVisible = false
      this.$nextTick(() => {
        this.resetForm()
      })
    },

    /**
     * 前往记录页面
     */
    goToRecords() {
      // 先关闭成功对话框
      this.successDialogVisible = false
      
      // 等待DOM更新完成后再跳转
      this.$nextTick(() => {
        this.$router.push({
          path: '/nfc/coupon/records',
          query: { 
            refresh: Date.now() // 强制刷新参数
          }
        })
      })
    },

    /**
     * 返回上一页
     */
    goBack() {
      this.$router.go(-1)
    },

    /**
     * 验证表单
     */
    validateForm() {
      return new Promise((resolve) => {
        this.$refs.consumeForm.validate((valid) => {
          resolve(valid)
        })
      })
    },

    /**
     * 处理优惠券代码输入
     */
    handleCouponCodeBlur() {
      // 实现优惠券代码输入后的逻辑
    },

    /**
     * 显示二维码扫描器
     */
    showQrScanner() {
      this.qrScannerVisible = true
      this.qrForm.qr_data = '' // 清空手动输入的数据
    },

    /**
     * 开始摄像头扫码
     */
    async startScan() {
      try {
        this.showScanner = true

        // 检查是否支持摄像头
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
          this.$message.error('您的浏览器不支持摄像头功能')
          this.showScanner = false
          return
        }

        // 获取摄像头列表
        const cameras = await QrScanner.listCameras(true)
        this.cameras = cameras

        if (cameras.length === 0) {
          this.$message.error('未检测到可用的摄像头')
          this.showScanner = false
          return
        }

        // 初始化扫描器
        const videoElement = document.getElementById('qr-scanner')
        this.scanner = new QrScanner(
          videoElement,
          result => this.handleScanResult(result),
          {
            returnDetailedScanResult: true,
            highlightScanRegion: true,
            highlightCodeOutline: true,
            preferredCamera: 'environment' // 优先使用后置摄像头
          }
        )

        await this.scanner.start()
        this.$message.success('扫码功能已启动，请将二维码对准摄像头')

      } catch (error) {
        console.error('启动扫码失败:', error)
        this.$message.error('启动摄像头失败，请检查权限设置或使用手动输入')
        this.showScanner = false
      }
    },

    /**
     * 停止摄像头扫码
     */
    stopScan() {
      if (this.scanner) {
        this.scanner.stop()
        this.scanner.destroy()
        this.scanner = null
      }
      this.showScanner = false
    },

    /**
     * 切换摄像头
     */
    async switchCamera() {
      if (this.cameras.length > 1 && this.scanner) {
        try {
          this.currentCamera = (this.currentCamera + 1) % this.cameras.length
          await this.scanner.setCamera(this.cameras[this.currentCamera].id)
          this.$message.success(`已切换到${this.cameras[this.currentCamera].label || '摄像头'}`)
        } catch (error) {
          console.error('切换摄像头失败:', error)
          this.$message.error('切换摄像头失败')
        }
      }
    },

    /**
     * 处理摄像头扫码结果
     */
    handleScanResult(result) {
      try {
        // 停止扫码
        this.stopScan()

        // 获取扫码结果数据
        const scanData = result.data || result
        console.log('扫码原始数据:', scanData)

        // 将扫码结果填入表单并自动解析
        this.qrForm.qr_data = scanData
        this.parseQrCode()

      } catch (error) {
        console.error('处理扫码结果失败:', error)
        this.$message.error('处理扫码结果失败，请重试')
      }
    },

    /**
     * 解析二维码
     */
    async parseQrCode() {
      this.qrParseLoading = true
      
      try {
        // 首先解析二维码数据
        const parseResponse = await parseCouponQrCode({
          qr_data: this.qrForm.qr_data
        })
        
        if (parseResponse.code === 200) {
          const qrData = parseResponse.data
          this.consumeForm.coupon_code = qrData.coupon_code
          
          // 设置商户ID，确保与下拉框匹配
          this.setMerchantFromQr(qrData.merchant_id)
          
          // 自动验证优惠券
          const verifyResponse = await apiVerifyCoupon({
            coupon_code: qrData.coupon_code,
            merchant_id: qrData.merchant_id
          })
          
          this.couponInfo = verifyResponse.data.coupon
          this.merchantInfo = verifyResponse.data.merchant
          this.canConsume = verifyResponse.data.can_consume
          this.verifyMessage = verifyResponse.message
          
          this.qrScannerVisible = false
          
          const merchant = this.merchantList.find(m => 
            m.id === qrData.merchant_id || m.id === String(qrData.merchant_id) || m.id === Number(qrData.merchant_id)
          )
          
          if (this.canConsume) {
            const merchantName = merchant ? merchant.merchant_name : `ID:${qrData.merchant_id}`
            
            // 自动填充用户信息
            if (verifyResponse.data.user_info) {
              const userInfo = verifyResponse.data.user_info
              if (userInfo.user_union_id || userInfo.user_openid) {
                this.consumeForm.user_union_id = userInfo.user_union_id || ''
                this.consumeForm.user_openid = userInfo.user_openid || ''
                this.$message.success(`二维码解析成功，已选择商户：${merchantName}，优惠券可以核销，已自动填充用户信息`)
              } else {
                this.$message.success(`二维码解析成功，已选择商户：${merchantName}，优惠券可以核销`)
              }
            } else {
              this.$message.success(`二维码解析成功，已选择商户：${merchantName}，优惠券可以核销`)
            }
          } else {
            this.$message.warning(this.verifyMessage)
          }
        } else {
          this.$message.error(parseResponse.message)
        }
        
      } catch (error) {
        this.$message.error(error.response?.data?.message || '二维码解析失败')
      } finally {
        this.qrParseLoading = false
      }
    },

    /**
     * 从查询参数设置商户
     */
    setMerchantFromQuery(merchantId) {
      console.log('来自查询参数的商户ID:', merchantId, '类型:', typeof merchantId)
      console.log('商户列表:', this.merchantList)
      
      // 尝试匹配商户（考虑数据类型转换）
      const merchant = this.merchantList.find(m => {
        return m.id === merchantId || m.id === String(merchantId) || m.id === Number(merchantId)
      })
      
      console.log('查找到的商户:', merchant)
      
      if (merchant) {
        // 使用商户列表中的实际ID值，确保数据类型一致
        this.consumeForm.merchant_id = merchant.id
        console.log('设置商户ID:', merchant.id, '类型:', typeof merchant.id, '商户名称:', merchant.merchant_name)
        console.log('表单最终数据:', this.consumeForm)
        this.$message.success(`已自动选择商户：${merchant.merchant_name}`)
        
        // 手动触发验证，确保表单状态正确
        this.$nextTick(() => {
          this.$refs.consumeForm.validateField('merchant_id')
        })
      } else {
        // 如果找不到商户，使用原始值（可能用于验证）
        this.consumeForm.merchant_id = Number(merchantId) || merchantId
        console.log('未找到商户，设置原始ID:', this.consumeForm.merchant_id, '类型:', typeof this.consumeForm.merchant_id)
        this.$message.warning(`商户ID：${merchantId}（商户列表中未找到对应商户）`)
      }
    },

    /**
     * 从二维码设置商户
     */
    setMerchantFromQr(merchantId) {
      console.log('来自二维码的商户ID:', merchantId, '类型:', typeof merchantId)
      console.log('商户列表:', this.merchantList)
      
      // 尝试匹配商户（考虑数据类型转换）
      const merchant = this.merchantList.find(m => {
        return m.id === merchantId || m.id === String(merchantId) || m.id === Number(merchantId)
      })
      
      console.log('查找到的商户:', merchant)
      
      if (merchant) {
        // 使用商户列表中的实际ID值，确保数据类型一致
        this.consumeForm.merchant_id = merchant.id
        console.log('设置商户ID:', merchant.id, '类型:', typeof merchant.id, '商户名称:', merchant.merchant_name)
        console.log('表单最终数据:', this.consumeForm)
        
        // 手动触发验证，确保表单状态正确
        this.$nextTick(() => {
          this.$refs.consumeForm.validateField('merchant_id')
        })
      } else {
        // 如果找不到商户，使用原始值（可能用于验证）
        this.consumeForm.merchant_id = Number(merchantId) || merchantId
        console.log('未找到商户，设置原始ID:', this.consumeForm.merchant_id, '类型:', typeof this.consumeForm.merchant_id)
      }
    }
  }
}
</script>

<style scoped>
.coupon-consume {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.consume-card {
  margin-bottom: 30px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
}

.form-section:last-child {
  border-bottom: none;
}

.form-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.coupon-info-section {
  margin: 30px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
}

.coupon-info-section h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.form-actions {
  text-align: center;
  margin-top: 40px;
}

.form-actions .el-button {
  margin: 0 10px;
}

/* 确认对话框样式 */
.confirm-content {
  text-align: center;
}

.confirm-details {
  margin: 20px 0;
  text-align: left;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
}

.confirm-details p {
  margin: 8px 0;
  font-size: 14px;
  color: #606266;
}

/* 成功对话框样式 */
.success-content {
  text-align: center;
}

.success-details {
  margin: 20px 0;
  text-align: left;
  background: #f0f9ff;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.success-details p {
  margin: 8px 0;
  font-size: 14px;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-section .el-col {
    margin-bottom: 15px;
  }
  
  .form-actions .el-button {
    margin: 5px;
    display: block;
    width: 100%;
  }
}

/* 二维码扫描对话框样式 */
.qr-scanner-container {
  padding: 20px;
  text-align: center;
  max-height: 80vh;
  overflow-y: auto;
}

.camera-scan-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
}

.scan-placeholder {
  padding: 40px 20px;
  text-align: center;
}

.scan-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 20px;
}

.scan-placeholder p {
  margin: 20px 0;
  color: #606266;
  font-size: 16px;
}

.scanner-container {
  margin: 20px 0;
}

.scanner-wrapper {
  position: relative;
  display: inline-block;
  margin: 0 auto;
}

.scanner-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.scan-frame {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  margin: -100px 0 0 -100px;
  border: 2px solid #409EFF;
  border-radius: 8px;
}

.scan-frame::before,
.scan-frame::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border: 3px solid #409EFF;
}

.scan-frame::before {
  top: -3px;
  left: -3px;
  border-right: none;
  border-bottom: none;
}

.scan-frame::after {
  bottom: -3px;
  right: -3px;
  border-left: none;
  border-top: none;
}

.scanner-controls {
  margin-top: 20px;
}

.scanner-controls .el-button {
  margin: 0 10px;
}

.scanner-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.manual-input-section {
  margin-top: 30px;
  padding-top: 20px;
  padding-bottom: 20px;
}

.qr-input-section {
  margin-bottom: 20px;
}

.qr-scanner-actions {
  text-align: center;
  margin-top: 25px;
}

.qr-scanner-actions .el-button {
  margin: 0 10px;
}

.camera-tip {
  margin-top: 10px;
  text-align: center;
  color: #909399;
}
</style> 